package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/tidwall/gjson"
)

const (
	//彩云api地址
	CaiyunURL = "#"
	//slack webhook地址
	WebhookURL = "#"
)

func main() {

	res, err := httpGet(CaiyunURL)
	sendStr := createSendMsg(res)
	err = SendSlackNotification(WebhookURL, sendStr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print("send successful!")
}

//请求彩云
func httpGet(url string) (*Weather, error) {
	resp, err := http.Get(url)
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("error: %s", resp.Status)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	// var result Caiyun
	// if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
	// 	return nil, err
	// }
	skycon := gjson.Get(string(body), "result.daily.skycon.0.value")
	skycon8h := gjson.Get(string(body), "result.daily.skycon_08h_20h.0.value")
	skycon32h := gjson.Get(string(body), "result.daily.skycon_20h_32h.0.value")
	maxTemp := gjson.Get(string(body), "result.daily.temperature.0.max")
	minTemp := gjson.Get(string(body), "result.daily.temperature.0.min")
	maxWind := gjson.Get(string(body), "result.daily.wind.0.max.speed")
	minWind := gjson.Get(string(body), "result.daily.wind.0.min.speed")
	ultraviolet := gjson.Get(string(body), "result.daily.ultraviolet.0.desc")
	pm25 := gjson.Get(string(body), "result.daily.pm25.0.avg")
	aqi := gjson.Get(string(body), "result.daily.aqi.0.avg")
	comfort := gjson.Get(string(body), "result.daily.comfort.0.desc")
	cloudrate := gjson.Get(string(body), "result.daily.cloudrate.0.avg")
	avgPrecipitation := gjson.Get(string(body), "result.daily.precipitation.0.avg")
	maxPrecipitation := gjson.Get(string(body), "result.daily.precipitation.0.max")
	date := gjson.Get(string(body), "result.daily.comfort.0.datetime")

	result := Weather{
		Skycon:           switchWeather(skycon.String()),
		Skycon8h:         switchWeather(skycon8h.String()),
		Skycon32h:        switchWeather(skycon32h.String()),
		MaxTemp:          maxTemp.String() + "°C",
		MinTemp:          minTemp.String() + "°C",
		MaxWind:          maxWind.Float(),
		MinWind:          minWind.Float(),
		Ultraviolet:      ultraviolet.String(),
		Pm25:             pm25.Float(),
		AQI:              aqi.Float(),
		Comfort:          comfort.String(),
		Cloudrate:        cloudrate.Float(),
		AvgPrecipitation: switchPrecipitation(avgPrecipitation.Float()),
		MaxPrecipitation: switchPrecipitation(maxPrecipitation.Float()),
		Date:             date.String(),
	}
	return &result, err
}

//天气状态翻译
func switchWeather(value string) string {
	var desc string
	switch value {
	case "CLEAR_DAY":
		desc = "晴（白天）"
	case "CLEAR_NIGHT":
		desc = "晴（夜间）"
	case "PARTLY_CLOUDY_DAY":
		desc = "多云（白天）"
	case "PARTLY_CLOUDY_NIGHT":
		desc = "多云（夜间）"
	case "CLOUDY":
		desc = "阴"
	case "WIND":
		desc = "大风"
	case "HAZE":
		desc = "雾霾"
	case "RAIN":
		desc = "雨"
	default:
		desc = "雪"
	}
	return desc
}

//紫外线转换
func switchUltraviolet(value byte) string {
	var desc string
	switch value {
	case 0:
		desc = "无（夜间）"
	case 1:
		desc = "最弱"
	case 2:
		desc = "弱"
	case 3:
		desc = "中等"
	case 4:
		desc = "强"
	default:
		desc = "很强"
	}
	return desc
}

//雨量转换
func switchPrecipitation(value float64) string {
	var desc string
	switch {
	case value < 0.03:
		desc = "无"
	case value >= 0.03 && value < 0.25:
		desc = "小雨（雪）"
	case value >= 0.25 && value < 0.35:
		desc = "小雨（雪）"
	case value >= 0.35 && value < 0.48:
		desc = "大雨（雪）"
	case value >= 0.48:
		desc = "暴雨（雪）"
	}
	return desc
}

//组装json
func createSendMsg(data *Weather) []byte {
	var sendMsg SendMsg
	sendMsg.Username = "每日天气"
	sendMsg.IconUrl = "https://dashboard.caiyunapp.com/static/image/IconColorCloud.png"
	var fields []Fields

	var attachments []Attachments

	fields = append(fields, Fields{"全天天气", data.Skycon, false})
	fields = append(fields, Fields{"白天天气", data.Skycon8h, true})
	fields = append(fields, Fields{"夜间天气", data.Skycon32h, true})
	fields = append(fields, Fields{"最高温度", data.MaxTemp, true})
	fields = append(fields, Fields{"最低温度", data.MinTemp, true})
	fields = append(fields, Fields{"最大风速", data.MaxWind, true})
	fields = append(fields, Fields{"最小风速", data.MinWind, true})
	fields = append(fields, Fields{"云量", data.Cloudrate, true})
	fields = append(fields, Fields{"紫外线", data.Ultraviolet, true})
	fields = append(fields, Fields{"平均降水量", data.AvgPrecipitation, true})
	fields = append(fields, Fields{"最大降水量", data.MaxPrecipitation, true})
	fields = append(fields, Fields{"PM25", data.Pm25, true})
	fields = append(fields, Fields{"空气指数", data.AQI, true})
	fields = append(fields, Fields{"舒适度", data.Comfort, false})

	attachments = append(attachments,
		Attachments{
			Fallback:   data.Date + " 天气预报",
			AuthorName: "彩云天气",
			Title:      data.Date + " 天气预报",
			Color:      "#36a64f",
			Fields:     &fields,
			Footer:     "彩云天气",
			FooterIcon: "https://dashboard.caiyunapp.com/static/image/IconColorCloud.png",
		})
	sendMsg.Attachments = &attachments

	str, _ := json.Marshal(sendMsg)
	return str
}
